<template>
    <div id="container">
        <div id="map-container" style=""></div>

    </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import eventBus from '@/eventBus/eventBus'
window._AMapSecurityConfig = {
    securityJsCode: '9c2d48cb0b0f4ee6a655bd05d6d9ee63',
}
export default {
    data () {
        return {
            map:null,
            autoOptions:{
                input:'',
                city:'重庆',
            },
            auto:null,
            placeSearch:null,
            searchInput:'',
            marker:null,
            infoWindow:null,
            address:'',
            locationValue:{},
            //两点之间距离标记
            marker1:null,
            marker2:null,
        }
    },
    methods:{
        initMap(){
            AMapLoader.load({
                key:"4f7348727c6c3f5443ccc99d94881068", // 申请好的Web端开发者Key，首次调用 load 时必填
                version:"2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins:[
                    'AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation','AMap.PlaceSearch','AMap.AutoComplete',
                    'AMap.Geocoder'
                ]
            }).then(AMap=>{
                this.map= new AMap.Map('map-container',{
                    viewMode:"3D", //是否为3D地图模式
                    zoom:14, 
                    center:[106.5574, 29.5604], // 设置成重庆渝中区
                })
                this.map.addControl(new AMap.Scale())
                this.map.addControl(new AMap.ToolBar())
                this.map.addControl(new AMap.HawkEye())
                this.map.addControl(new AMap.MapType())
                this.map.addControl(new AMap.Geolocation())
                this.auto = new AMap.AutoComplete(this.autoOptions)
                this.placeSearch = new AMap.PlaceSearch({
                    map: this.map
                })
                this.auto.on('select',this.select)
                this.map.on('click',e=>{
                    let lat = e.lnglat.lat
                    let lng = e.lnglat.lng
                    this.getAddressDetail(lat,lng)
                })
            }).catch(e =>{
                console.log(e)
            })
        },
        select(e){
            console.log(e)
            this.placeSearch.setCity(e.poi.city)
            this.placeSearch.search(e.poi.name) //关键字查询查询
            this.$message({
                message:'已为您定位到 '+e.poi.name,
                type:'success'
            })
            
        },
        //获取两点之间距离
        getDistance(){
            let distance = this.map.getDistance(this.marker1.getPosition(),this.marker2.getPosition())
            this.$message({
                message:'两点之间距离为 '+distance+' 米',
                type:'success'
            })
        },
        getAddressDetail(lat,lng){
            let lnglat = new AMap.LngLat(lng,lat)
            let geocoder = new AMap.Geocoder({
                city:'全国',                
            })
            if(this.marker){
                this.map.remove(this.marker)
            }
            this.marker = new AMap.Marker({
                position: new AMap.LngLat(lng,lat),
            })
            this.marker.on('click',()=>{this.showInfoWindow(this.address)})
            this.map.add(this.marker)            
            geocoder.getAddress(lnglat,(status,result)=>{
                if(status=='complete'&&result.regeocode){
                    let address = result.regeocode.formattedAddress
                    this.address = address
                    this.showInfoWindow(address)
                    this.$message({
                        showClose:true,
                        message:'已为您定位到 '+address,
                        type:'success'
                    })
                    
                    // 在获取到地址后立即更新位置信息并发送给父组件
                    this.updateLocationValue(address, lng, lat)
                }else{
                    this.$message({
                        showClose:true,
                        message:'定位失败',
                        type:'error'
                    })
                }
            })
        },
        showInfoWindow(address){
            // 创建新的 InfoWindow
            this.infoWindow = new AMap.InfoWindow({
                content: address,
                anchor: 'top-center',
                autoMove: true,
            });
            // 打开 InfoWindow
            this.infoWindow.open(this.map, this.marker.getPosition());
        },
        updateLocationValue(address, lng, lat) {
            const regex = /^(.*?省|.*?市|.*?自治区)(.*?市|.*?自治州|.*?区|.*?县|.*?旗)(.*?街道|.*?镇|.*?乡|.*?村|.*?路|.*?道|.*?路街道|.*?道街道)(?:.*?)(.*)$/;
            let match = address.match(regex);
                    
            if (match) {
                const city = match[1];
                const district = match[2];
                const street = match[3];
                const detail = match[4];
                
                this.locationValue = {
                    address: address,
                    lng: lng,
                    lat: lat,
                    city: city,
                    district: district,
                    street: street,
                    detail: detail,
                    fullAddress: address
                }
            } else {
                // 即使地址格式不规范，也传递完整地址
                this.locationValue = {
                    address: address,
                    lng: lng,
                    lat: lat,
                    fullAddress: address
                }
            }
            
            // 发送位置数据给父组件
            console.log('发送的位置数据:', JSON.stringify(this.locationValue));
            this.$emit('location-update', this.locationValue);
        },
        updateValue(){
            console.log('选择按钮被点击');
            
            if (!this.marker) {
                console.error('没有选择位置，marker 为空');
                this.$message.warning('请先在地图上选择一个位置');
                return;
            }
            
            // 如果 locationValue 已经有值，直接发送
            if (Object.keys(this.locationValue).length > 0) {
                console.log('发送的位置数据:', JSON.stringify(this.locationValue));
                this.$emit('location-update', this.locationValue);
            } else {
                // 如果 locationValue 为空，重新获取地址信息
                const lng = this.marker.getPosition().lng;
                const lat = this.marker.getPosition().lat;
                this.updateLocationValue(this.address, lng, lat);
            }
        }
    },
    mounted(){
        this.initMap()
    },
    created(){
        eventBus.$on('search',val=>{
            this.autoOptions.input=val.searchId
            this.searchInput = val.keyword
        })
    },
    watch:{
        searchInput(val){
            if(val!=null){
                this.placeSearch.search(val)
                this.$message({
                    showClose:true,
                    message:'已为您搜索到有关 '+val+' 的地点',
                    type:'success'
                })
                
            }            
        },
        showInfoWindowByClick(){
            this.marker.on('click',this.showInfoWindow(this.address))
        }
    }
}
</script>

<style lang="less" scoped>
#container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

}
#map-container {
    flex: 1;
    position: relative;
    width: 80vw;
    height: 50vh; // 设置一个固定高度
}
</style>